/**
 * 
 */
package com.lanswon.qzsmk.service.systemManageService.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ch.qos.logback.classic.Logger;

import com.lanswon.qzsmk.base.SystemManageContants;
import com.lanswon.qzsmk.dao.DataPrivilegeMapper;
import com.lanswon.qzsmk.dao.RolePrivilegeMapper;
import com.lanswon.qzsmk.dao.SysPermissionMapper;
import com.lanswon.qzsmk.model.RolePrivilege;
import com.lanswon.qzsmk.model.SysPermission;
import com.lanswon.qzsmk.service.systemManageService.PrivilegeManageService;
import com.lanswon.qzsmk.vo.MenuVo;

/**
 * @author sun
 *
 */
@Service
public class PrivilegeManageServiceImpl implements PrivilegeManageService {

	@Autowired
	DataPrivilegeMapper dpm;

	@Autowired
	SysPermissionMapper spm;

	@Autowired
	RolePrivilegeMapper rpm;

	private static Logger logger = (Logger) LoggerFactory.getLogger(PrivilegeManageServiceImpl.class);

	// @Override
	// public void saveDataPrivilege(DataPrivilege dp) throws Exception {
	// // if(dpm.queryCountByAcs(dp.getAcs()) != 0){
	// // throw new ApplicationException(ErrorCode.DUPLICATION_DATA,
	// // "["+dp.getAcs()+ "] already exsits");
	// // }
	// dpm.insert(dp);
	// }

	// @Override
	// public boolean existPrivilegeResource(String resource) throws Exception {
	// if (dpm.queryCountByAcs(resource) != 0) {
	// return true;
	// }
	// return false;
	// }

	@Override
	public void saveDataPrivilege_1(SysPermission record) {
		spm.insert(record);

	}

	@Override
	public boolean existPrivilegeResource_1(String resource) throws Exception {
		if (spm.queryCountByResource(resource) != 0) {
			return true;
		}
		return false;
	}

	@Override
	public boolean existPrivilegeName(String name) throws Exception {
		if (spm.queryCountByName(name) != 0) {
			return true;
		}
		return false;
	}

	@Override
	public List<MenuVo> querySysPermissionMenus() {
		List<SysPermission> list = spm.querySysPermissionMenus(SystemManageContants.PERMISSIONS_TYPE_MENU);// 所有菜单

		List<MenuVo> rootMenu = new ArrayList<>();
		List<MenuVo> menuList = new ArrayList<>();

		for (SysPermission s : list) {
			MenuVo vo = new MenuVo();
			vo.setId(s.getPrivilegeId());
			vo.setName(s.getPrivilegeName());
			vo.setParentId(s.getParentid());
			vo.setOrder(s.getSorting());
			vo.setUrl(s.getPrivilegeResource());
			vo.setSelected(SystemManageContants.NOT_SELECTED);
			vo.setPrivilegeTypeName(s.getPrivilegeTypeName());
			rootMenu.add(vo);

		}

		for (int i = 0; i < rootMenu.size(); i++) {
			// 一级菜单没有parentId
			if (rootMenu.get(i).getParentId() == null) {
				menuList.add(rootMenu.get(i));
			}
		}

		for (MenuVo menu : menuList) {
			menu.setChildMenus(getChild(menu.getId(), rootMenu));

		}

		return menuList;
	}

	private List<MenuVo> getChild(Integer id, List<MenuVo> rootMenu) {
		// 子菜单
		List<MenuVo> childList = new ArrayList<>();
		for (MenuVo menu : rootMenu) {
			// 遍历所有节点，将父菜单id与传过来的id比较
			if (menu.getParentId() != null) {
				if (menu.getParentId().equals(id)) {
					childList.add(menu);
				}
			}
		}
		// 把子菜单的子菜单再循环一遍
		for (MenuVo menu : childList) {// 没有url子菜单还有子菜单
			if (StringUtils.isBlank(menu.getUrl())) {
				// 递归
				menu.setChildMenus(getChild(menu.getId(), rootMenu));
			}
		} // 递归退出条件
		if (childList.size() == 0) {
			return null;
		}

		return childList;
	}

	@Override
	public void setAuthForRole(RolePrivilege rp) {

		SysPermission s = spm.querySysPermissionById(rp.getPrivilegeId());
		String percode = s.getPercode();
		String percode_key = s.getPercode().substring(0, percode.indexOf(":"));
		List<SysPermission> list = spm.likeQuerySysPermissionByPercode(percode_key);
//		List<SysPermission> ll = spm.likeQuerySysPermissionByName("基础查询");
//		// 如果不存在就添加
//		if (rpm.duplicatePermissionForRole(ll.get(0).getPrivilegeId(), rp.getRoleId()) == 0) {
//			list.addAll(ll);
//		}

		for (SysPermission aa : list) {
			RolePrivilege a = new RolePrivilege();
			a.setPrivilegeId(aa.getPrivilegeId());
			a.setRoleId(rp.getRoleId());
			a.setSysId(rp.getSysId());
			rpm.insert(a);
		}

	}

	@Override
	public void cancelAuthForRole(RolePrivilege rp) {
		
		SysPermission s = spm.querySysPermissionById(rp.getPrivilegeId());
		String percode = s.getPercode();
		String key_code = percode.substring(0, percode.indexOf(":"));
		List<SysPermission> list = spm.likeQuerySysPermissionByPercode(key_code);
		for(SysPermission a :list){
		rp = new RolePrivilege(a.getPrivilegeId(),rp.getSysId(),rp.getRoleId());
			rpm.delete(rp);
		}
		
	}

	@Override
	public List<Integer> querySysPermissionByRoleId_1(Integer roleId) {
		Long sh = System.currentTimeMillis();
		
		List<Integer> lm = new ArrayList<>();
		
		List<SysPermission> ll = spm.querySysPermissionByRoleId(roleId, SystemManageContants.PERMISSIONS_TYPE_MENU);
		for(SysPermission sp:ll){
			lm.add(sp.getPrivilegeId());
		}
		
		logger.debug("------------------------------时间差【{}】",System.currentTimeMillis()-sh);
		return lm;
	}

	@Override
	public List<MenuVo> querySysPermissionByRoleId(Integer roleId) {
		Long sh = System.currentTimeMillis();
		List<RolePrivilege> lr = rpm.queryRolePrivilegeByRoleId(roleId);
		List<MenuVo> lm = new ArrayList<>();
		for (RolePrivilege r : lr) {
			SysPermission s = spm.querySysPermissionByType(r.getPrivilegeId(),
					SystemManageContants.PERMISSIONS_TYPE_MENU);
			if (s != null) {
				MenuVo vo = new MenuVo();
				vo.setId(s.getPrivilegeId());
				vo.setName(s.getPrivilegeName());
				vo.setParentId(s.getParentid());
				vo.setOrder(s.getSorting());
				vo.setUrl(s.getPrivilegeResource());
				vo.setSelected(SystemManageContants.ALL_SELECTED);
				lm.add(vo);

			}

		}
		logger.debug("*********************************************lm长度{}", lm.size());

		List<MenuVo> ll = ggg(lm);
		logger.debug("--------------好多个菜单{}", ll.size());
		lm.addAll(ll);
		logger.debug("----------------------******--------时间差【{}】",System.currentTimeMillis()-sh);

		return lm;
	}

	

	//
	private List<MenuVo> ggg(List<MenuVo> lm) {
		List<MenuVo> lll = new ArrayList<>();
		logger.debug("111111111111111111111111111111111111111111");
		// if(lm.size()==1){
		// Integer pId = lm.get(0).getParentId();
		// List<SysPermission> se = spm.queryPermissionMenusByParentId(pId,
		// SystemManageContants.PERMISSIONS_TYPE_MENU);
		// SysPermission sss = spm.querySysPermissionById(pId);
		// if(se.size()==lm.size()){
		// MenuVo o = new MenuVo();
		// o.setId(sss.getPrivilegeId());
		// o.setName(sss.getPrivilegeName());
		// o.setParentId(sss.getParentid());
		// o.setOrder(sss.getSorting());
		// o.setUrl(sss.getPrivilegeResource());
		// o.setSelected(SystemManageContants.ALL_SELECTED);
		// lll.add(o);
		// }else if(se.size()>lm.size()){
		// MenuVo o = new MenuVo();
		// o.setId(sss.getPrivilegeId());
		// o.setName(sss.getPrivilegeName());
		// o.setParentId(sss.getParentid());
		// o.setOrder(sss.getSorting());
		// o.setUrl(sss.getPrivilegeResource());
		// o.setSelected(SystemManageContants.PART_SELECTED);
		// lll.add(o);
		//
		// SysPermission aa = spm.querySysPermissionById(sss.getPrivilegeId());
		//
		// SysPermission aa1 = spm.querySysPermissionById(aa.getParentid());
		//
		//
		// }
		// logger.debug("############llllllllll长度{}:",lll.size());
		// // lll = ggg(lll);
		// }else{
		//

		for (int i = 0; i < lm.size() - 1; i++) {
			logger.debug("便利lm{}", lm.get(i).getId());
			Set<MenuVo> l = new HashSet<>();
			for (int j = lm.size() - 1; j > i; j--) {
				if (lm.get(j).getParentId().equals(lm.get(i).getParentId())) {
					logger.debug("---------{}同一个父目录{}", lm.get(j).getId(), lm.get(i).getId());
					l.add(lm.get(j));
					l.add(lm.get(i));
				}
			}
			logger.debug(";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;");
			Integer parentId = lm.get(i).getParentId();
			logger.debug("parentIdparentIdparentId:{}", parentId);
			List<SysPermission> se = spm.queryPermissionMenusByParentId(parentId,
					SystemManageContants.PERMISSIONS_TYPE_MENU);
			logger.debug("{}--------{}", l.size(), se.size());
			SysPermission sss = spm.querySysPermissionById(parentId);// 上一级

			if (l.size() == se.size()) {
				logger.debug("全部选中");
				MenuVo o = new MenuVo();
				o.setId(sss.getPrivilegeId());
				o.setName(sss.getPrivilegeName());
				o.setParentId(sss.getParentid());
				o.setOrder(sss.getSorting());
				o.setUrl(sss.getPrivilegeResource());
				o.setSelected(SystemManageContants.ALL_SELECTED);
				lll.add(o);

				lll.addAll(ggg(lll));

			} else if (l.size() < se.size() && l.size() > 0) {
				logger.debug("部分选中");
				MenuVo o = new MenuVo();
				o.setId(sss.getPrivilegeId());
				o.setName(sss.getPrivilegeName());
				o.setParentId(sss.getParentid());
				o.setOrder(sss.getSorting());
				o.setUrl(sss.getPrivilegeResource());
				o.setSelected(SystemManageContants.PART_SELECTED);
				lll.add(o);
				lll.addAll(ggg(lll));
			}

		}
		// }
		logger.debug("2222222222222222222222222222222222222222");
		return lll;

	}

	
	@Override
	public Map<String, Object> checkNameAndSave(List<SysPermission> list, SysPermission sy) {
		Map<String, Object> map=new HashMap<>();
		boolean b = false;
		for(SysPermission s:list){
			if(sy.getPrivilegeName().equalsIgnoreCase(s.getPrivilegeName())){
				b= true;
				sy=s;
				break;
			}
		}
		
		
		if(!b){
			spm.insert(sy);
			list.add(sy);
			}
		map.put("sy", sy);
		map.put("list", list);
		return  map;
		
	}

	
	@Override
	public List<SysPermission> queryAllSysPermission() {
		return spm.queryAllSysPermission();
	}
}